<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类列表-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="name"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--文章列表-->
      <!-- 查询 -->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入文章标题"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="文章作者" prop="author">
            <el-input
              v-model="queryParams.author"
              placeholder="请输入文章作者"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="文章状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="文章状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-s-claim"
              size="mini"
              :disabled="multiple"
              @click="handleRelease"
            >发布</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <!-- 列表 -->
        <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="文章编号"
            align="center"
            key="postsId"
            prop="postsId"
            v-if="columns[0].visible"
            width="80"
          />
          <el-table-column
            label="文章标题"
            align="center"
            key="title"
            prop="title"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="文章作者"
            align="center"
            key="author"
            prop="author"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="是否评论"
            align="center"
            key="isComment"
            v-if="columns[3].visible"
            width="160"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isComment"
                active-value="0"
                inactive-value="1"
                @change="handleIsCommentChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="文章状态"
            key="status"
            :formatter="statusFormat"
            width="160"
            v-if="columns[4].visible"
          ></el-table-column>
          <el-table-column
            label="排序"
            align="center"
            key="sort"
            prop="sort"
            v-if="columns[5].visible"
          />
          <el-table-column
            label="浏览次数"
            align="center"
            key="views"
            prop="views"
            v-if="columns[6].visible"
          />
          <el-table-column
            label="评论次数"
            align="center"
            key="comments"
            prop="comments"
            v-if="columns[7].visible"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[8].visible"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
              <el-button
                v-if="scope.row.status == 1"
                size="mini"
                type="text"
                icon="el-icon-s-claim"
                @click="handleRelease(scope.row)"
              >发布</el-button>
              <el-button
                v-if="scope.row.status == 0"
                size="mini"
                type="text"
                icon="el-icon-s-release"
                @click="handleOff(scope.row)"
              >下架</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 创建 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawer"
      :direction="direction"
      size="80%"
      ref="drawer"
      custom-class="my-drawer"
    >
      <div class="my-drawer__content">
        <el-form ref="form" :model="form" :rules="rules" size="mini" label-position="top">
          <el-row>
            <el-col :span="24">
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入标题" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="总结">
                <el-input type="textarea" :rows="2" v-model="form.summary" placeholder="请输入导语" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :gutter="20">
              <el-form-item label="是否评论">
                <el-radio-group v-model="form.isComment">
                  <el-radio
                    v-for="dict in commentOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" :gutter="20">
              <el-form-item label="排序">
                <el-input-number v-model="form.sort" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分类">
                <el-cascader
                  v-model="form.categories"
                  :options="categoryOptions"
                  :props="{ multiple: true, checkStrictly: true, value: 'id' }"
                  placeholder="请选择文章分类"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="标签">
                <el-select
                  v-model="form.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择文章标签"
                  @change="tagsChange"
                >
                  <el-option
                    v-for="item in tagOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="封面图">
                <el-upload
                  class="cover-uploader"
                  :headers="upload.headers"
                  :action="upload.url"
                  :show-file-list="false"
                  :on-success="handleCoverSuccess"
                  :before-upload="beforeCoverUpload"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="cover" />
                  <i v-else class="el-icon-plus cover-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="内容">
                <mavon-editor
                  ref="markdown"
                  v-model="form.content"
                  :ishljs="true"
                  :toolbars="markdownOption"
                  :box-shadow="false"
                  :subfield="false"
                  placeholder="开始你的表演"
                  style="height: 835px;z-index: 5"
                  @imgAdd="$imgAdd"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="my-drawer__footer">
        <el-button @click="cancelForm">关闭</el-button>
        <el-button
          type="primary"
          @click="submitForm"
          :loading="addLoading"
        >{{ addLoading ? '保存中 ...' : '保存' }}</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listPosts, addPosts, changeIsComment, releasePosts, delPosts, offPosts, getPosts, updatePosts } from "@/api/posts/posts";
import { treeSelect } from "@/api/posts/category";
import { mavonEditor } from 'mavon-editor';
import { allTags } from "@/api/posts/tag";
import { uploadPicture } from "@/api/upload";
import { markdownOption } from "./toolbars";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Post",
  components: { Treeselect, mavonEditor },
  data () {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        author: undefined,
        status: undefined,
        categoryId: undefined,
      },
      // 显示搜索条件
      showSearch: true,
      // 状态数据字典
      statusOptions: [
        { dictLabel: "发布", dictValue: "0" },
        { dictLabel: "草稿", dictValue: "1" }
      ],
      // 是否
      commentOptions: [
        { dictLabel: "是", dictValue: "0" },
        { dictLabel: "否", dictValue: "1" }
      ],
      // 日期范围
      dateRange: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 列信息
      columns: [
        { key: 0, label: `文章编号`, visible: true },
        { key: 1, label: `文章标题`, visible: true },
        { key: 2, label: `文章作者`, visible: true },
        { key: 3, label: `是否评论`, visible: true },
        { key: 4, label: `文章状态`, visible: true },
        { key: 5, label: `排序`, visible: true },
        { key: 6, label: `浏览次数`, visible: false },
        { key: 7, label: `评论次数`, visible: false },
        { key: 8, label: `创建时间`, visible: true }
      ],
      // 遮罩层
      loading: true,
      // 文章表格数据
      postList: null,
      // 总条数
      total: 0,
      // 表单参数
      form: {},
      // 分类名称
      name: undefined,
      // 分类树选项
      categoryOptions: undefined,
      // 标签选项
      tagOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      //增加修改抽屉
      drawer: false,
      //抽屉方向
      direction: "rtl",
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
      },
      //抽屉名
      drawerTitle: '',
      // 文章保存遮罩层
      addLoading: false,
      // markdown编辑选项
      markdownOption: markdownOption,
      // 选中数组
      ids: [],
      // 选中标题
      titles: [],
      // 封面上传参数
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/blog/upload/picture"
      },
      // 封面图
      imageUrl: '',
      // markdown编写
      activeName: 'edit'
    }
  },
  watch: {
    // 根据名称筛选部门树
    name (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.getList();
    this.getTreeselect();
    this.getTagList();
  },
  methods: {
    /** 获取标签列表 */
    getTagList () {
      allTags().then(response => {
        this.tagOptions = response.data
      })
    },
    /** 查询分类下拉树结构 */
    getTreeselect () {
      treeSelect().then(response => {
        this.categoryOptions = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询用户列表 */
    getList () {
      this.loading = true;
      listPosts(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.queryParams.categoryId = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset () {
      this.form = {
        title: undefined,
        summary: undefined,
        isComment: 1,
        sort: 1,
        categories: undefined,
        tags: undefined,
        thumbnail: undefined,
        content: undefined
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.imageUrl = '';
      this.drawer = true;
      this.drawerTitle = "新增文章";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.drawer = true;
      this.drawerTitle = "修改文章";
      getPosts(row.postsId).then(response => {
        this.form = response.data;
        this.imageUrl = process.env.VUE_APP_BASE_API + this.form.thumbnail;
        this.form.content = response.content;
        this.form.tags = response.tags;
        this.form.categories = response.categories;
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const postsIds = row.postsId || this.ids;
      const postTitles = row.title || this.titles;
      this.$confirm('是否确认删除标题"' + postTitles + '"的文章?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delPosts(postsIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 发布 */
    handleRelease (row) {
      const postsIds = row.postsId || this.ids;
      const postTitles = row.title || this.titles;
      this.$confirm('确认要发布"' + postTitles + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return releasePosts(postsIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("发布成功");
      }).catch(() => {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 下架重回草稿
    handleOff (row) {
      this.$confirm('确认要下架"' + row.title + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return offPosts(row.postsId);
      }).then(() => {
        this.getList();
        this.msgSuccess("下架成功");
      }).catch(() => {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.postsId);
      this.titles = selection.map(item => item.title)
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 是否评论
    handleIsCommentChange (row) {
      let text = row.isComment === "1" ? "停用" : "启用";
      this.$confirm('确认要' + text + '"' + row.title + '"评论吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeIsComment(row.postsId, row.isComment);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(() => {
        row.isComment = row.isComment === 1 ? 0 : 1;
      });
    },
    // 文章状态字典翻译
    statusFormat (row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick (data) {
      this.queryParams.categoryId = data.id;
      this.getList();
    },
    // 表单提交
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.addLoading = true;
          this.form.thumbnail = this.imageUrl.replace(process.env.VUE_APP_BASE_API, '');
          if (this.form.postsId != undefined) {
            updatePosts(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.drawer = false;
              this.addLoading = false;
              this.getList();
            }).catch(() => {
              this.addLoading = false;
            })
          } else {
            addPosts(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.drawer = false;
              this.addLoading = false;
              this.getList();
            }).catch(() => {
              this.addLoading = false;
            })
          }
        }
      });
    },
    // 取消
    cancelForm () {
      this.drawer = false;
      this.addLoading = false;
      this.imageUrl = '';
      this.reset();
    },
    // 刷新表单
    reset () {
      this.imageUrl = '';
      this.form = {};
      this.resetForm("form");
    },
    $imgAdd (pos, $file) {
      var formdata = new FormData();
      formdata.append('file', $file);
      uploadPicture(formdata).then(response => {
        this.$refs.markdown.$img2Url(pos, response.imgUrl);
      })
    },
    // 导入markdown
    handleExport (row) {

    },
    // 成功上传封面图
    handleCoverSuccess (response, file) {
      this.imageUrl = process.env.VUE_APP_BASE_API + response.imgUrl;
      this.msgSuccess("上传成功");
    },
    beforeCoverUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.msgError('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.msgError('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 标签选择器变化
    tagsChange () {
      this.$forceUpdate();
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.my-drawer {
  padding: 10px 0px 0px 0px;
}
.my-drawer__content {
  padding: 30px 30px 60px 30px;
}
.my-drawer__footer {
  padding: 10px 0px 10px 0px;
  position: absolute;
  bottom: 0;
  background-color: white;
  width: 100%;
  z-index: 10;
  text-align: center;
  .el-button {
    width: 200px;
  }
}
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409eff;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.cover {
  width: 178px;
  height: 178px;
  display: block;
}
</style>